package com.think.oauth.user.service;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.think.oauth.user.dao.user.RoleDao;
import com.think.oauth.user.model.Permission;
import com.think.oauth.user.model.Role;
import com.think.oauth.user.model.RolePermission;

@Service
public class RoleService extends ServiceImpl<RoleDao,Role>{
	
	@Autowired
	private RolePermissionService rolePermissionService;
	
	public boolean SaveNewRole(Role role,Integer[] pers) {
		try {
			this.save(role);
			Collection<RolePermission> rolePermissions = new ArrayList<>();
			for (Integer per : pers) {
				RolePermission rolePermission = new RolePermission();
				rolePermission.setRoleId(role.getRoleId());
				rolePermission.setPermissionId(per);
				rolePermission.setCreator(role.getCreator());
				rolePermission.setUpdator(role.getUpdator());
				rolePermissions.add(rolePermission);
			}
			rolePermissionService.saveBatch(rolePermissions);
		} catch (Exception e) {
			// TODO: handle exception
			
		}
		return true;
	}
	
	public boolean updateRole(Role role,Integer[] pers) {
		try {
			this.updateById(role);
			rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("role_id", role.getRoleId()));
			Collection<RolePermission> rolePermissions = new ArrayList<>();
			for (Integer per : pers) {
				RolePermission rolePermission = new RolePermission();
				rolePermission.setRoleId(role.getRoleId());
				rolePermission.setPermissionId(per);
				rolePermission.setUpdator(role.getUpdator());
				rolePermissions.add(rolePermission);
			}
			rolePermissionService.saveBatch(rolePermissions);
		} catch (Exception e) {
			// TODO: handle exception
			
		}
		return true;
	}
	
	public ArrayList<Permission> getRolePers(Integer roleId){
		return rolePermissionService.getBaseMapper().getPermissionsByRoleId(roleId);
	}

}
